package web.admin.config;

import dao.inte.TemplateRepository;
import domain.Template;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.ConfigurationService;

import java.util.logging.Level;
import java.util.logging.Logger;

public class TemplateForm extends Form {
    @SpringBean
    private TemplateRepository templateRepository;
    @SpringBean
    private ConfigurationService configurationService;
    private static final Logger logger = Logger.getLogger(TemplateForm.class.getName());

    String fileName;
    private IModel<Template> templateModel;

    public TemplateForm(String id, final String fileName) {
        super(id);
        this.fileName = fileName;
        templateModel = new LoadableDetachableModel<Template>() {
            @Override
            protected Template load() {
                try {
                    return templateRepository.findByKey(fileName);
                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", TemplateForm.this));
                    return null;
                }
            }
        };

        TextArea templateTextArea = new TextArea("templateInput", new PropertyModel(templateModel, "value"));
        add(templateTextArea.setEscapeModelStrings(false));
    }

    @Override
    protected void onSubmit() {
        try {
            templateRepository.save(templateModel.getObject());
            info(getLocalizer().getString("saved", this));
        }
        catch (Exception e) {
            Logger.getLogger(ConfigurationPanel.class.getName()).log(Level.SEVERE, null, e);
            error(getLocalizer().getString("system.error", this));
        }
    }

}
